package com.saifan.wyy_ov.ui.communitylife;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.saifan.wyy_ov.R;
import com.saifan.wyy_ov.config.Api;
import com.saifan.wyy_ov.data.bean.BBSListRequestBean;
import com.saifan.wyy_ov.data.bean.BBSPostBean;
import com.saifan.wyy_ov.data.bean.BBSThemesBean;
import com.saifan.wyy_ov.data.bean.PermissionsBean;
import com.saifan.wyy_ov.model.impl.GetData;
import com.saifan.wyy_ov.model.interfaces.IGetData;
import com.saifan.wyy_ov.model.interfaces.ResponseData;
import com.saifan.wyy_ov.ui.view.BaseActivity;
import com.saifan.wyy_ov.ui.view.RefreshLayout;
import com.saifan.wyy_ov.ui.zoomimage.ZoomImageActivity;
import com.saifan.wyy_ov.utils.CircleProgressBottomDialog;
import com.saifan.wyy_ov.utils.CommonAdapter;
import com.saifan.wyy_ov.utils.LogUtil;
import com.saifan.wyy_ov.utils.StringUtil;
import com.saifan.wyy_ov.utils.TimeUtils;
import com.saifan.wyy_ov.utils.ToastUtil;
import com.saifan.wyy_ov.utils.ViewHolderHelper;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0.0
 * @author: Wangli
 * @date: 2015-6-9 19:54:46
 * @descrption 论坛帖子列表页面
 */

public class BBSListActivity extends BaseActivity {
    private android.support.v7.widget.Toolbar toolbar;
    private android.widget.ListView listView;
    private com.saifan.wyy_ov.ui.view.RefreshLayout refreshLayout;
    private int page = 0;
    private BBSListRequestBean requestBean;
    private IGetData getData;
    private BBSThemesBean bean;
    private CommonAdapter<BBSPostBean> adapter;
    private List<BBSPostBean> list;
    private boolean initFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bean = (BBSThemesBean) getIntent().getExtras().getSerializable("data");
        setupViews();
        initData();
    }

    private void setupViews() {
        setContentView(R.layout.activity_bbslist);
        this.refreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        this.listView = (ListView) findViewById(R.id.listView);
        this.toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle(bean.getLTBK_MC());
        list = new ArrayList<BBSPostBean>();
        adapter = new CommonAdapter<BBSPostBean>(BBSListActivity.this, list, R.layout.bbs_list_item) {
            @Override
            public void convert(ViewHolderHelper helper, BBSPostBean item) {
                helper.setText(R.id.nick_name, StringUtil.returnShow(item.getWYKHDA_LC()));
                helper.setText(R.id.time, TimeUtils.getTime(item.getFTB_FTSJ()));
                helper.setText(R.id.title, StringUtil.returnShow(item.getFTB_BT()));
                helper.setText(R.id.content, StringUtil.returnShow(item.getFTB_LR()));
                helper.setText(R.id.comments_count, String.format(getResources().getString(R.string.publish_comments_count), item.getPLTS()));
                helper.setImageByUrl(R.id.header, item.getWYKHDA_TXLJ());
                LinearLayout imgs = helper.getView(R.id.imgs);
                imgs.setVisibility(StringUtil.isNullOrEmpty(item.getFTB_TPLJ()) ? View.GONE : View.VISIBLE);
                if (!StringUtil.isNullOrEmpty(item.getFTB_TPLJ())) {
                    final String[] imgsPath = item.getFTB_TPLJ().split(",");
                    for (int i = 0; i < 4; i++) {
                        int id = getResources().getIdentifier("img" + i, "id", BBSListActivity.this.getPackageName());
                        if (i < imgsPath.length) {
                            helper.getView(id).setVisibility(View.VISIBLE);
                            helper.setImageByUrl(id, imgsPath[i]);
                            final int finalI = i;
                            helper.getView(id).setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(BBSListActivity.this, ZoomImageActivity.class);
                                    ArrayList<String> imgs = new ArrayList<String>();
                                    for (int m = 0; m < imgsPath.length; m++) {
                                        imgs.add(imgsPath[m]);
                                    }
                                    intent.putStringArrayListExtra("img", imgs);
                                    intent.putExtra("position", finalI);
                                    startActivity(intent);
                                }
                            });
                        } else {
                            helper.getView(id).setVisibility(View.INVISIBLE);
                        }
                    }
                }

            }
        };
        listView.setAdapter(adapter);
        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 0;
                refreshLayout.setRefreshing(true);
                initData();
            }
        });
        refreshLayout.setOnLoadListener(new RefreshLayout.OnLoadListener() {
            @Override
            public void onLoad() {
                CircleProgressBottomDialog.showDialog(BBSListActivity.this);
                if (page > 0)
                    refreshLayout.setLoading(true);
                page++;
                initData();
            }
        });
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Intent intent = new Intent(BBSListActivity.this, BBSDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", (Serializable) list.get(i));
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }

    private void initData() {
        String tip;
        if (getData == null)
            getData = new GetData();
        if (requestBean == null) {
            requestBean = new BBSListRequestBean();
            requestBean.setFTB_LTBKWJ(bean.getLTBK_ZJ());
        }
        if (initFlag)
            tip = "";
        else
            tip = "正在加载...";
        requestBean.setPage(page);
        getData.getDataJson(this, Api.BBS.POSTSLIST, requestBean, tip, new ResponseData() {
            @Override
            public void onSuccess(String json) {
                LogUtil.d("论坛列表" + json);
                if (StringUtil.isNullOrEmpty(json)) {
                    if (page == 0) {
                        handler.sendEmptyMessage(0);//没有数据
                    } else {
                        page--;
                        handler.sendEmptyMessage(1);//没有更多数据
                    }
                } else {
                    Message message = handler.obtainMessage();
                    List<BBSPostBean> tempList = (new Gson()).fromJson(json, new TypeToken<List<BBSPostBean>>() {
                    }.getType());
                    if (page == 0) {//下拉刷新
                        if (tempList != null && tempList.size() > 0) {
                            message.what = 2;
                            message.obj = tempList;
                        } else {
                            message.what = 0;
                        }
                    } else {//加载更多
                        if (tempList != null && tempList.size() > 0) {
                            message.what = 3;
                            message.obj = tempList;
                        } else {
                            message.what = 1;
                            page--;
                        }
                    }
                    handler.sendMessage(message);
                    CircleProgressBottomDialog.closeDialog();
                }
                initFlag = true;
            }

            @Override
            public void onFailed(String str) {
                refreshLayout.setRefreshing(false);
                refreshLayout.setLoading(false);
                CircleProgressBottomDialog.closeDialog();
                if (page >= 0) {
                    page--;
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_bbslist, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_publish) {
            if (getRoomInfoBean().getUserType() == 2){
                for (PermissionsBean permissionsBean : getPermissions()){
                    if (permissionsBean.getYKQX_GNMC().equals("业主论坛")){
                        Intent intent = new Intent(BBSListActivity.this, BBSPublishActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("data", bean);
                        intent.putExtras(bundle);
                        startActivity(intent);
                        return true;
                    }
                }
                ToastUtil.showToast(BBSListActivity.this, "您的权限不能进行此操作");
                return true;
            } else if (getRoomInfoBean().getUserType() == 3){
                ToastUtil.showToast(BBSListActivity.this, "您的权限不能进行此操作");
                return true;
            }


            Intent intent = new Intent(BBSListActivity.this, BBSPublishActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("data", bean);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        return super.onOptionsItemSelected(item);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    ToastUtil.showToast(BBSListActivity.this, "暂无相关数据");
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 1:
//                    ToastUtil.showToast(BBSListActivity.this, "暂无更多数据");
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 2:

                    list = (List<BBSPostBean>) msg.obj;
                    adapter.mDatas = list;
                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                case 3:
                    list.addAll((List<BBSPostBean>) msg.obj);
                    adapter.mDatas = list;
                    adapter.notifyDataSetChanged();
                    refreshLayout.setRefreshing(false);
                    refreshLayout.setLoading(false);
                    break;
                default:
                    break;
            }
        }
    };
}
